<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Created by PhpStorm.
 * User: steven
 * Date: 2016/3/25
 * Time: 22:34
 */
class Wechat
{
    public function __construct()
    {
        $CI = get_instance();
        $CI->load->model('access_token_model');
        $CI->load->helper('url_helper');
    }

    public function valid() {
        if(isset($_GET["echostr"])){
            $echoStr = $_GET["echostr"];
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        }
        exit;
    }
    private function checkSignature() {
        if(!isset($_GET["signature"])){
            return false;
        }
        $signature = $_GET["signature"];
        if(!isset($_GET["timestamp"])){
            return false;
        }
        $timestamp = $_GET["timestamp"];
        if(!isset($_GET["nonce"])){
            return false;
        }
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ) {
            return true;
        } else {
            return false;
        }
    }


    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
            if($keyword == "?" || $keyword == "？")
            {
                $msgType = "text";
                $contentStr = date("Y-m-d H:i:s",time());
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }
        }else{
            echo "";
            exit;
        }
    }

    public function get_access_token(){
        $access_token_row=$this->access_token_model->get_access_token;
        $expire_time=$access_token_row['expire_time'];
        if($expire_time<time()){
            $accessToken=$this->get_new_access_token();
            $data=array(
                'id'=>$access_token_row['id'],
                'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
                'expire_time'=>date("Y-m-d H:i:s" ,time()+7200),
                'access_token'=>$accessToken
            );
            $result=$this->access_token_model->update_access_token($data);
            if($result){
                return $accessToken;
            }else{
                return "";
            }
        }else{
            return $access_token_row['access_tokens'];
        }

    }
    public function get_new_access_token(){
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
        $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
//echo $res;
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        $access_token = $result['access_token'];
        return $access_token;
    }
    public function  expire_access_token(){
        $access_token_row=$this->access_token_model->get_access_token;
        if(!isset($access_token_row)){
            return false;
        }
        $data=array(
            'id'=>$access_token_row['id'],
            'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
            'expire_time'=>date("Y-m-d H:i:s" ,time())
        );
        $result=$this->access_token_model->update_access_token($data);
        if($result){
            return true;
        }else{
            return false;
        }
    }

}